import 'package:flutter/material.dart';
import 'package:flutterprojectportal/support/scheme_util.dart';

import 'logger.dart';

typedef Widget PageBuilder(String pageName, Map params, String uniqueId);

class RouteManager {
  static Map<String, PageBuilder> _pageBuilders = <String, PageBuilder>{};

  static void initRoute(Map<String, PageBuilder> map) {
    _pageBuilders = map;
  }

//   Map<String, PageBuilder>  get pageBuilders => _pageBuilders;

  /// Android跳转flutter页面，路由规则：flutterpage://path?key1=value1&ke2=value2 其中value需要做urlencode
  static Route<dynamic> onGenerateRoute(RouteSettings settings) {
    final String actionUrl = settings.name; //window.defaultRouteName;

    Logger.dev("origin route ==> $actionUrl");

    String routeName = SchemeUtil.getPath(actionUrl) ?? actionUrl;
//    if(routeName == null) return null;

    var arguments = SchemeUtil.getQueryParameter(actionUrl);
    if (arguments?.isNotEmpty == true) {
      settings = RouteSettings(
          name: routeName ?? settings.name, arguments: arguments);
    }
    if (_pageBuilders.containsKey(routeName)) {
      return MaterialPageRoute(
          settings: settings, // 可以在build中通过ModalRoute.of(context).settings.arguments获取
          builder: (BuildContext context) {
            PageBuilder builder = _pageBuilders[routeName];
            return builder(routeName, arguments, null);
          });
    }
    return null;
  }
}
